<?php
namespace Tools\Upload;

use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;

class QnUpload

{   //图片访问域名
    const QN_DOMAIN = 'http://7sblc3.com1.z0.glb.clouddn.com/';
    //最大上传2M
    const UPLOAD_MAX_SIZE = '2097152';
    const ACCESS_KEY = 'uVwVZIT1su97cYYxFpBE6_IG4p4cb2dqCE3lw1w8';
    const SECRET_KEY = 'zNgqMr2Ml7agcmrg209hAw9EkrXawwaBuZPGS4j8';
    const BUCKET = 'ichevp';

    public function upload($fileInfo)
    {
        $ext = strrchr($fileInfo['name'], '.');
        //二进制流存放到本地。不过如果多台服务器就有问题
        if(isset($fileInfo['data']) && !empty($fileInfo['data'])) {
            $data = $fileInfo['data'];
            $filePath = sys_get_temp_dir() . '/' . time() . $ext;
            file_put_contents($filePath, $data);
            $fileInfo['size'] = filesize($filePath);
            $fileInfo['type'] = filetype($filePath);
        } else {
            $data = file_get_contents($fileInfo['tmp_name']); // 取得文件内容
            $filePath = $fileInfo['tmp_name'];
        }

        $sha1 = strtr(rtrim(base64_encode(sha1($data, true)), '='), '+/', '-_');
        $fileName = $sha1 . $ext;


        if($fileInfo['size'] > static::UPLOAD_MAX_SIZE) {
            return $this->responseMessage(10002, '上传图片最大2M');
        }

        $auth = new Auth(static::ACCESS_KEY, static::SECRET_KEY);
        // 生成上传Token
        $token = $auth->uploadToken(static::BUCKET);
        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $fileName, $filePath);
        $filePath && unlink($filePath);
        if(!empty($err)) {
            return $this->responseMessage(10001, '上传失败', $err);
        }

        $ret['type'] = $fileInfo['type'];
        $ret['size'] = $fileInfo['size'];
        $ret['fileName'] = $fileName;
        $ret['url'] = $this->getFileFullUrl($fileName);
        $ret['ext'] = trim($ext, '.');
        return $this->responseMessage(0, '上传成功', $ret);
    }

    /**
     * 返回数据
     * @param int $code
     * @param null $msg
     * @param null $data
     * @return array
     */
    public function responseMessage($code = 0, $msg = null, $data = null)
    {
        return compact('code', 'msg', 'data');
    }

    /**
     * @param $uri
     */
    protected function getFileFullUrl($uri)
    {
        return empty($uri) ? '' : static::QN_DOMAIN . $uri;
    }
}